package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
)

type IShippingTemplatesRepository interface {
	Find(db *gorm.DB) ([]*model.ShippingTemplates, error)
	FindPage(db *gorm.DB, params *pagehelper.Params) ([]*model.ShippingTemplates, error)
	Count(db *gorm.DB, params *pagehelper.Params) (int64, error)
	Updates(db *gorm.DB, id uint, columns map[string]interface{}) error
	FindById(db *gorm.DB, id uint) (*model.ShippingTemplates, error)
	BatchDelete(db *gorm.DB, ids []uint) error
}

type ShippingTemplatesRepository struct {
}

func NewShippingTemplatesRepository() IShippingTemplatesRepository {
	return &ShippingTemplatesRepository{}
}

func (r *ShippingTemplatesRepository) Find(db *gorm.DB) (rows []*model.ShippingTemplates, err error) {
	return rows, db.Model(&model.ShippingTemplates{}).Find(&rows).Error
}

func (r *ShippingTemplatesRepository) FindPage(db *gorm.DB, params *pagehelper.Params) (page []*model.ShippingTemplates, err error) {
	tx := db.Model(&model.ShippingTemplates{}).Where(params.WherePair.Query, params.WherePair.Args...)
	return page, tx.Scopes(pagehelper.Paginate(params.Current, params.Size)).
		Order("seq desc").Order("created_at desc").Find(&page).Error
}

func (r *ShippingTemplatesRepository) Count(db *gorm.DB, params *pagehelper.Params) (count int64, err error) {
	tx := queryWrapper.ReuseSelect(db.Model(&model.ShippingTemplates{}), params.SelectFields)
	return count, queryWrapper.ReuseWherePair(tx, params.WherePair).Count(&count).Error
}

func (r *ShippingTemplatesRepository) Updates(db *gorm.DB, id uint, columns map[string]interface{}) error {
	return db.Model(&model.ShippingTemplates{}).Where("id = ?", id).Updates(columns).Error
}

func (r *ShippingTemplatesRepository) FindById(db *gorm.DB, id uint) (row *model.ShippingTemplates, err error) {
	return row, db.First(&row, id).Error
}

func (r *ShippingTemplatesRepository) BatchDelete(db *gorm.DB, ids []uint) error {
	return db.Delete(&model.ShippingTemplates{}, ids).Error
}
